package indi.zhifa.engine.core.excel.handler;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONWriter;
import indi.zhifa.engine.core.excel.entity.BaseExcelSheetRowData;
import indi.zhifa.engine.core.excel.entity.enums.EExcelErrorCode;
import indi.zhifa.engine.core.excel.entity.exception.ExcelException;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;

import java.lang.reflect.Field;

@Slf4j
public class IntegerCellHandler implements IExcelCellHandler {

    @Override
    public Object handle(Cell pCell,Class pClass) {
        if(null == pCell){
            return null;
        }
        if(pCell.getCellType() == CellType.NUMERIC || pCell.getCellType() == CellType.FORMULA){
            return (int)pCell.getNumericCellValue();
        }else if(pCell.getCellType() == CellType.STRING){
            String cellVal = pCell.getStringCellValue();
            if(!StrUtil.isBlankIfStr(cellVal)){
                return 0;
            }
            try{
                int iVal = Integer.parseInt(cellVal);
                return iVal;
            }catch (NumberFormatException ex){
                throw new ExcelException(EExcelErrorCode.CELL_TYPE_FAILED,cellVal+" 无法被转换为数字");
            }
        }else if(pCell.getCellType() == CellType._NONE || pCell.getCellType() == CellType.BLANK){
            return null;
        }
        return null;
    }

    @Override
    public void fill(Cell pCell, BaseExcelSheetRowData pRowData, Field pField) throws IllegalAccessException {
        Object data = pField.get(pRowData);
        if(null != data){
            Integer iData = (Integer) data;
            if(null != iData){
                pCell.setCellValue(iData);
            }else{
                log.error("对象的字段 "+pField.getName()+" 不是整型, \n"+ JSON.toJSONString(pRowData, JSONWriter.Feature.PrettyFormat));
            }
        }

    }

}
